﻿using rbac.domain.Entity;
using rbac.domain.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace rbac.domain.Impl
{
    public class RoleRepository : IRoleRepository
    {

        public readonly RbacContext _context;

        public RoleRepository(RbacContext context)
        {
            _context = context;
        }

        public int Add(Role entity)
        {
            _context.Roles.Add(entity);
            return _context.SaveChanges();
        }
        public int Update(Role entity)
        {
            var role= _context.Roles.FirstOrDefault(x => x.Id == entity.Id);
            role.RoleName=entity.RoleName;
            role.Remark=entity.Remark;
            role.UpdateTime=DateTime.Now;
            return _context.SaveChanges();
        }

        public IQueryable<Role> Roles()
        {
            return _context.Roles;
        }

        public List<Role> SearchRoles(string roleName)
        {
            var roles=_context.Roles.AsQueryable();
            if (!string.IsNullOrEmpty(roleName))
            {
                roles = roles.Where(x => x.RoleName.Contains(roleName));
            }

            return roles.ToList();
        }

        public int Delete(int loginUserId, params int[] idlist)
        {
            if (idlist.Length <= 0)
            {
                return 0;
            }
            var roles = _context.Roles.Where(x => idlist.Contains(x.Id));
            foreach ( var role in roles)
            {
                role.IsDeleted = true;
                role.UpdatedUserId = loginUserId;
                role.UpdateTime= DateTime.Now;
            }
            return _context.SaveChanges();
        }
    }
}
